package com.dhh.toodledo.activity;

import java.util.Date;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.dhh.toodledo.R;
import com.dhh.toodledo.exception.InValidAccountException;
import com.dhh.toodledo.manager.TaskManager;
import com.dhh.toodledo.model.Task;
import com.dhh.toodledo.util.AuthUtil;
import com.dhh.toodledo.util.CUtil;
import com.flurry.android.FlurryAgent;

import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem.Type;

public class ShowTaskDetailActivity extends GDActivity implements View.OnClickListener{
	private ProgressDialog progressDialog;
	private SharedPreferences sp;
	private AuthUtil au;
	private TaskManager tManager;
	private String taskId = "";
	private Task task;
	
	@Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setActionBarContentView(R.layout.task_detail);
        tManager = new TaskManager();
        sp = getSharedPreferences("myPre", 0);
        au = new AuthUtil(sp);
        initActionBar();
        initView();
        taskId = getIntent().getExtras().getString("taskId");
    	(new SearchThread()).start();
	}
	
	@Override
    public void onStart(){
       super.onStart();
       FlurryAgent.onStartSession(this, "2ND7X5T2HQCRXGXJ1BUF");
    }
    
    @Override
    public void onStop(){
       super.onStop();
       FlurryAgent.onEndSession(this);
    }
	
	@Override
	public void onClick(View v) {
		if(R.id.td_done_lst==v.getId()){
			if(task.getCompleted()>0){
	    		findViewById(R.id.td_done).setBackgroundResource(R.drawable.ic_checkbox_empty);
	    	}else{
	    		findViewById(R.id.td_done).setBackgroundResource(R.drawable.ic_checkbox_full);
	    	}
			new UpdateTask().execute("done");

		}else if(R.id.td_star_lst==v.getId()){
			if(task.getStar()==1){
	    		findViewById(R.id.td_star).setBackgroundResource(android.R.drawable.star_big_off);
	    	}else{
	    		findViewById(R.id.td_star).setBackgroundResource(android.R.drawable.star_big_on);
	    	}
			new UpdateTask().execute("star");		
		}else if(R.id.td_priority_lst==v.getId()){			
			showPriorityDialog("");
		}else if(R.id.td_duedate_lst==v.getId()){			
			showDateDailog("", v).show();
		}else if(R.id.td_startdate_lst==v.getId()){			
			showDateDailog("", v).show();
		}else if(R.id.td_note_lst==v.getId()){			
			getAlertDialogTextEdit("",task.getNote(),v).show();
		}else if(R.id.td_name==v.getId()){			
			getAlertDialogTextEdit("",task.getNote(),v).show();
		}
		
	}   
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id){
			case 0:
				progressDialog = new ProgressDialog(this);
				progressDialog.setTitle("Deleting Task ....");
				progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				return progressDialog;			
		}
		
		return null;		
	}
	
	public void initActionBar(){
		getActionBar().setTitle("Task Details");
		getActionBar().setGravity(Gravity.CENTER_HORIZONTAL);
        getActionBar().setBackgroundColor(Color.rgb(9, 135, 205));
        getActionBar().addItem(Type.Trashcan).getItemView().setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				showDialog(0);
				(new DeleteTask()).execute(new String[]{});
			}});
        getActionBar().getChildAt(0).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ShowTaskDetailActivity.this,TDAActivity.class);
				startActivity(intent);
			}});
	}
	
	private Handler eHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	Intent intent = new Intent(ShowTaskDetailActivity.this,LoginActivity.class);
        	ShowTaskDetailActivity.this.startActivity(intent);
        }
    };
    
    private Handler nHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	Intent intent = new Intent(ShowTaskDetailActivity.this,TDAActivity.class);
        	ShowTaskDetailActivity.this.startActivity(intent);
        }
    };
    
	private class SearchThread extends Thread {
        @Override
        public void run() {  
        	try {
				task = tManager.getTask(au.getKeyValue(), taskId);
	        	handler.sendEmptyMessage(0);
			} catch (InValidAccountException e) {
				eHandler.sendEmptyMessage(0);
			}catch (Exception e) {
				nHandler.sendEmptyMessage(0);
			}
        }        
    }
        
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	fillData();
        	ShowTaskDetailActivity.this.findViewById(R.id.td_loading).setVisibility(View.GONE);
        	ShowTaskDetailActivity.this.findViewById(R.id.dd_content).setVisibility(View.VISIBLE);
        }
    };
    
    private Handler rHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	Intent intent = new Intent(ShowTaskDetailActivity.this,TDAActivity.class);
        	ShowTaskDetailActivity.this.startActivity(intent);
        	progressDialog.dismiss();
        }
    };
    
    private void fillData(){
    	((TextView)findViewById(R.id.td_name)).setText(task.getTitle());
    	((TextView)findViewById(R.id.td_priority)).setText(task.getPriorityTitle());
    	((TextView)findViewById(R.id.td_date_start)).setText(task.getStartdateTitle(sp.getInt("dateformat", 0)));
    	((TextView)findViewById(R.id.td_date_due)).setText(task.getDuedateTitle(sp.getInt("dateformat", 0)));
    	((TextView)findViewById(R.id.td_note)).setText(task.getNote());
    	if(task.getStar()==1){
    		findViewById(R.id.td_star).setBackgroundResource(android.R.drawable.star_big_on);
    	}else{
    		findViewById(R.id.td_star).setBackgroundResource(android.R.drawable.star_big_off);
    	}
    	
    	if(task.getCompleted()>0){
    		findViewById(R.id.td_done).setBackgroundResource(R.drawable.ic_checkbox_full);
    	}else{
    		findViewById(R.id.td_done).setBackgroundResource(R.drawable.ic_checkbox_empty);
    	}
    	
    }

	private void initView(){
		findViewById(R.id.td_done_lst).setOnClickListener(this);
		findViewById(R.id.td_star_lst).setOnClickListener(this);
		findViewById(R.id.td_priority_lst).setOnClickListener(this);
		findViewById(R.id.td_duedate_lst).setOnClickListener(this);
		findViewById(R.id.td_startdate_lst).setOnClickListener(this);
		findViewById(R.id.td_note_lst).setOnClickListener(this);
		findViewById(R.id.td_name).setOnClickListener(this);
	}    
	
	private class UpdateTask extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... params) {
			try {
				if("done".equals(params[0])){
					task = tManager.markDone(au.getKeyValue(),task.getId(), !(task.getCompleted()>0));
				}else if("star".equals(params[0])){
					task = tManager.markStar(au.getKeyValue(),task.getId(), Long.valueOf(task.getStar()==0?1:0));
				}else if("priority".equals(params[0])){
					task = tManager.updateTask(au.getKeyValue(),task.getId(), null, null,task.getPriority(),null,null);
				}else if("date".equals(params[0])){
					task = tManager.updateTask(au.getKeyValue(),task.getId(), task.getStartdate(), task.getDuedate(),null,null,null);
				}else if("note".equals(params[0])){
					task = tManager.updateTask(au.getKeyValue(),task.getId(), null, null,null,task.getNote(),null);
				}else if("title".equals(params[0])){
					task = tManager.updateTask(au.getKeyValue(),task.getId(), null, null,null,task.getNote(),task.getTitle());
				}
				handler.sendEmptyMessage(0);
			} catch (InValidAccountException e) {
				eHandler.sendEmptyMessage(0);
			}
			
			return "All Done!";
		}
	}
	
	private class DeleteTask extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... params) {
			try {
				tManager.deleteTask(au.getKeyValue(),task.getId());
				rHandler.sendEmptyMessage(0);
			} catch (InValidAccountException e) {
				eHandler.sendEmptyMessage(0);
			}
			
			return "All Done!";
		}
	}
	
	int selectedItem = 0;
    private void showPriorityDialog(String title){		
    	String[] pv = {"Negative","Low","Medium","High","Top"};
    	selectedItem = task.getPriority().intValue()+1;
		AlertDialog.Builder ab = new AlertDialog.Builder(ShowTaskDetailActivity.this);
		ab.setTitle(title);		
		ab.setSingleChoiceItems(pv, task.getPriority().intValue()+1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						selectedItem = whichButton;
					}
				})
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						task.setPriority(Long.valueOf(selectedItem-1));
						fillData();
						new UpdateTask().execute("priority");
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
							}
						});
		ab.show();
	}    
    
    AlertDialog showDateDailog(String title,final View v){
		final LayoutInflater li = LayoutInflater.from(this);
        final View categoryDetailView = li.inflate(R.layout.date_pick, null);	
        DatePicker datePicker = (DatePicker) categoryDetailView.findViewById(R.id.wa_date);
        Date date = new Date();
        if(v.getId()==R.id.td_duedate_lst){
        	date = CUtil.getDate(task.getDuedate());
		}else if(v.getId()==R.id.td_startdate_lst){
        	date = CUtil.getDate(task.getStartdate());
		}
        
        int year = 1900 + date.getYear();
        int month = date.getMonth();
        int day = date.getDate(); 
        datePicker.init(year, month, day, null);        
		
		AlertDialog.Builder builder = new AlertDialog.Builder(ShowTaskDetailActivity.this);
		builder.setView(categoryDetailView).setTitle(title).
			setPositiveButton("OK", new DialogInterface.OnClickListener(){		    	 
            @Override
            public void onClick(DialogInterface d, int which) {
            	DatePicker datePicker = (DatePicker) categoryDetailView.findViewById(R.id.wa_date);
        		if(v.getId()==R.id.td_duedate_lst){
        			Date pDate = CUtil.getDate(task.getDuedate());
        			pDate.setYear(datePicker.getYear()-1900);
        			pDate.setMonth(datePicker.getMonth());
        			pDate.setDate(datePicker.getDayOfMonth());
        			task.setDuedate(Long.valueOf(CUtil.getStamp(pDate)));
        		}else if(v.getId()==R.id.td_startdate_lst){
        			Date pDate = CUtil.getDate(task.getStartdate());
        			pDate.setYear(datePicker.getYear()-1900);
        			pDate.setMonth(datePicker.getMonth());
        			pDate.setDate(datePicker.getDayOfMonth());
        			task.setStartdate(Long.valueOf(CUtil.getStamp(pDate)));
        		}
        		fillData();
        		new UpdateTask().execute("date");
            }
	    }).
	    setNegativeButton("Cancel", new DialogInterface.OnClickListener(){		    	 
            @Override
            public void onClick(DialogInterface d, int which) {
            	d.dismiss();
            }
	    });
		return builder.create();
	}
    
    AlertDialog getAlertDialogTextEdit(String title,String value,final View view){
		final FrameLayout fl = new FrameLayout(ShowTaskDetailActivity.this);
		final EditText input = new EditText(ShowTaskDetailActivity.this);
		input.setSingleLine(false);
		input.setLines(8);
		input.setGravity(Gravity.TOP);
		input.setText(value);
		fl.addView(input, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.FILL_PARENT));
		
		AlertDialog.Builder builder = new AlertDialog.Builder(ShowTaskDetailActivity.this);
		builder.setView(fl).setTitle(title).
			setPositiveButton("OK", new DialogInterface.OnClickListener(){		    	 
                @Override
                public void onClick(DialogInterface d, int which) {    
                	if(view.getId()==R.id.td_note_lst){
                		task.setNote(input.getText().toString());
            			fillData();
    					new UpdateTask().execute("note");
                    	
                	}else if(view.getId()==R.id.td_name){
                		task.setTitle(input.getText().toString());
            			fillData();
    					new UpdateTask().execute("title");
                	}
                	d.dismiss();
                }
		    }).
		    setNegativeButton("Cancel", new DialogInterface.OnClickListener(){		    	 
                @Override
                public void onClick(DialogInterface d, int which) {
                	d.dismiss();
                }
		    });
		
		return builder.create();
	}
    
    
	
}
